import { saveAs } from 'file-saver';
import { mapActions, mapGetters } from 'vuex';
import { getRoleList } from '@/api/system/tbSysRole';
import { addRolesByUsers } from '@/api/system/tbSysUserRole';
import { batchUpdateDepart, batchUpdateLevel, updateUser } from '@/api/system/tbSysUser';
import { banAndRecoveryUser, updateUserPassword, exportUser } from '@/api/system/tbSysUser';
export default {
	data() {
		return {
			roleListData: [],
			checkedRoles: null,
			checkedLevel: null,
			checkedDepart: null
		}
	},
	async created() {
		await this.getRoleListData();
	},
	computed: {
		...mapGetters(['departTree']),
		levelListData() {
			return this.dictData['TB_SYS_USER_LEVEL'] || [];
		}
	},
	methods: {
		...mapActions(['getConstByCode']),
		//获取角色列表数据
		async getRoleListData() {
			let params = { page: 1, limit: 9999 };
			let result = await getRoleList(params).then((res) => res.data);
			if (result.code === '0') {
				this.roleListData = result.data || [];
			}
		},

		//封禁/恢复
		handleBanAndRecoveryUser(id, del, title) {
			let that = this;
			this.$confirm(`此操作将${title}该用户, 是否继续？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				async beforeClose(action, instance, done) {
					if (action === 'confirm') {
						let data = { id, del, title };
						instance.confirmButtonLoading = true;
						await that.banAndRecoveryRequest(data);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//封禁/恢复请求
		async banAndRecoveryRequest(data) {
			let params = [{ id: data.id, del: data.del }];
			let result = await banAndRecoveryUser(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`${data.title}账号成功`);
				this.queryTableData();
			}
		},

		//还原删除用户
		handleRestoreDelete(data) {
			this.handleBanAndRecoveryUser(data.id, '1', '还原');
		},

		//重置用户密码
		handleResetUserPassword(id) {
			this.$confirm(`此操作将重置该用户密码, 是否继续？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.resetUserPasswordRequest(id);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//批量配置用户密码
		handleBatchResetPassword() {
			this.$confirm(`此操作将批量重置该用户密码, 是否继续？`, '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.resetUserPasswordRequest();
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//格式化用户密码参数
		async formatResetPasswordParams(id) {
			let passData = await this.getConstByCode('USER_PASSWORD');
			if (!id) {
				let userPasswords = this.selectedUser.map(n => {
					return { id: n.id, password: passData?.value }
				});
				return Promise.resolve(userPasswords);
			} else {
				return Promise.resolve([{ id, password: passData?.value }]);
			}
		},

		//重置用户密码请求
		async resetUserPasswordRequest(id) {
			let params = await this.formatResetPasswordParams(id);
			let result = await updateUserPassword(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`重置密码成功`);
				this.queryTableData();
			}
		},

		//创建角色选择组件
		createRoleSelect(arr) {
			this.checkedRoles = [...arr];
			return this.$createElement('swCustomSelect', {
				props: { options: this.roleListData, value: this.checkedRoles },
				attrs: { multiple: true, placeholder: '请选择用户角色' },
				style: { width: '100%' },
				on: {
					input: (value) => {
						this.checkedRoles = value;
					}
				}
			})
		},

		//批量配置用户角色
		handleBatchConfigRoles() {
			let dataArr = [];
			this.$msgbox({
				title: '批量配置角色',
				message: this.createRoleSelect(dataArr),
				showCancelButton: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.batchConfigRolesRequest();
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//批量配置用户角色请求
		async batchConfigRolesRequest() {
			let roleIds = this.checkedRoles || [];
			let userIds = this.selectedUser.map(n => n.id);
			let userRoles = roleIds.map(n => userIds.map(m => ({ userId: m, roleId: n })));
			let params = userRoles.reduce((prev, cur) => prev.concat(cur), []);
			let result = await addRolesByUsers(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`批量配置角色成功`);
				this.checkedRoles = [];
				this.queryTableData();
			}
		},

		//配置用户角色
		handleConfigUserRoles(data) {
			let dataArr = data.menuRoleList.map(n => n.id);
			this.$msgbox({
				title: '消息',
				message: this.createRoleSelect(dataArr),
				showCancelButton: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.configUserRolesRequest(data);
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//配置单个用户角色请求
		async configUserRolesRequest(data) {
			let roleIds = this.checkedRoles || [];
			let params = { id: data.id, roleIds };
			let result = await updateUser(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`批量配置角色成功`);
				this.queryTableData();
			}
		},

		//创建部门选择组件
		createDepartSelect() {
			return this.$createElement('swSearchTreeSelect', {
				props: {
					filterable: true,
					value: this.checkedDepart,
					treeData: this.departTree,
					placeholder: '请选择用户部门',
					defaultProps: { label: 'name', children: 'childList' },
				},
				style: { width: '100%' },
				on: {
					input: (value) => {
						this.checkedDepart = value;
					}
				}
			})
		},

		//批量配置部门
		handleBatchConfigDepart() {
			this.$msgbox({
				title: '批量配置部门',
				message: this.createDepartSelect(),
				showCancelButton: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.configUserDepartRequest();
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		//配置用户部门请求
		async configUserDepartRequest() {
			let params = this.selectedUser.map(n => {
				return { id: n.id, deptId: this.checkedDepart }
			});
			let result = await batchUpdateDepart(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`批量配置部门成功`);
				this.queryTableData();
			}
		},

		//创建用户等级选择组件
		createLevelSelect() {
			return this.$createElement('swCustomSelect', {
				props: {
					value: this.checkedLevel,
					options: this.levelListData,
					props: { label: 'deName', value: 'deValue' }
				},
				attrs: { placeholder: '请选择用户等级' },
				style: { width: '100%' },
				on: {
					input: (value) => {
						this.checkedLevel = value;
					}
				}
			})
		},

		//批量配置用户等级
		handleBatchConfigLevel() {
			this.$msgbox({
				title: '批量配置用户等级',
				message: this.createLevelSelect(),
				showCancelButton: true,
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				beforeClose: async (action, instance, done) => {
					if (action === 'confirm') {
						instance.confirmButtonLoading = true;
						await this.configUserLevelRequest();
						instance.confirmButtonLoading = false;
						done();
					} else {
						done();
					}
				}
			}).catch(() => {});
		},

		async configUserLevelRequest() {
			let params = this.selectedUser.map(n => {
				return { id: n.id, level: this.checkedLevel }
			});
			let result = await batchUpdateLevel(params).then(res => res.data);
			if (result.code === '0') {
				this.$message.success(`批量配置用户等级成功`);
				this.queryTableData();
			}
		},

		//导入用户
		handleImportUser() {
			this.importDialog = true;
		},

		formatExportMessage(data) {
			let text = '您现在正准备导出';
			if (!data.deptId && !data.userName && !data.account && !data.type && !data.sex && !data.del) {
				text += '所有';
			}
			if (!!data.deptId) {
				let departData = this.$findNodeInTree(this.departTree, data.deptId, 'childList');
				text += `<<font color="#930b0b">部门为${departData?.name || '--'}</font>>`;
			}
			if (!!data.userName) {
				text += `<<font color="#930b0b">用户姓名包含${data.userName}</font>>`;
			}
			if (!!data.account) {
				text += `<<font color="#930b0b">用户账号包含${data.account}</font>>`;
			}
			if (!!data.type) {
				let typeArr = this.dictData['TB_SYS_USER_TYPE'];
				let typeData = typeArr.find(n => n.deValue === data.type);
				text += `<<font color="#930b0b">用户类型为${typeData?.deName}</font>>`;
			}
			if (!!data.sex) {
				let sexArr = this.dictData['TB_SYS_USER_SEX'];
				let sexData = sexArr.find(n => n.deValue === data.sex);
				text += `<<font color="#930b0b">用户性别为${sexData?.deName}</font>>`;
			}
			if (!!data.del) {
				let delName = data.del === '1' ? '可用' : (data.del === '2' ? '禁用' : '');
				text += `<<font color="#930b0b">用户状态为${delName}</font>>`;
			}
			return text + '的用户数据';
		},

		//导出用户
		handleExportUser() {
			let params = { ...this.queryData };
			let baseUrl = process.env.VUE_APP_BASE_API;
			let message = this.formatExportMessage(params);
			this.$alert(message, '导出用户数据', {
				dangerouslyUseHTMLString: true,
				callback: (action, instance) => {
					if (action !== 'confirm') return false;
					delete params.page;
					delete params.limit;
					exportUser(params).then(res => {
						saveAs(res.data, '用户数据.xls');
					});
				}
			})
		}
	}
}